<template>
	<view :class="{'page-box':true,bottom: !disabled}">
		<view class="input-box">
			<view class="input-box-title">基础信息</view>
			<view class="input-item">
				<view class="label">仓库</view>
				<view class="input-icon">
					<view class="input">
						<picker :value="form.id" :disabled="disabled || stateData == 'addMore'" :range="cangkus" range-key="label" @change="cangkuChange">
							<view class="uni-input">{{cangkus[form.id]?.label}}</view>
						</picker>
					</view>
					<view :class="{ 'icon iconfont icon-youjiantou': true, 'hide': disabled }"></view>
				</view>
			</view>
			<view class="input-item">
				<view class="label">类型</view>
				<view class="input-icon">
					<view class="input">
						<picker :value="form.type" :disabled="disabled" :range="types" range-key="label" @change="typeChange">
							<view class="uni-input">{{types[form.type]?.label}}</view>
						</picker>
					</view>
					<view :class="{ 'icon iconfont icon-youjiantou': true, 'hide': disabled }"></view>
				</view>
			</view>
			<view class="input-item">
				<view class="label">原因</view>
				<view class="input-icon">
					<view class="input">
						<picker :value="form.status" :disabled="disabled" :range="statusArr" range-key="label" @change="statusChange">
							<view class="uni-input">{{statusArr[form.status]?.label}}</view>
						</picker>
					</view>
					<view :class="{ 'icon iconfont icon-youjiantou': true, 'hide': disabled }"></view>
				</view>
			</view>
			<view class="input-item">
				<view class="label"><text class="must">*</text>名称</view>
				<view class="input-icon">
					<input class="input" v-model="form.name" :disabled="disabled"  placeholder="请输入内容" />
					<view class="icon hide iconfont icon-youjiantou"></view>
				</view>
			</view>
			<view class="input-item">
				<view class="label"><text class="must">*</text>数量</view>
				<view class="input-icon">
					<input class="input" type="digit" v-model="form.count" :disabled="disabled" placeholder="请输入内容" />
					<view class="icon hide iconfont icon-youjiantou"></view>
				</view>
			</view>
			<view class="input-item">
				<view class="label"><text class="must">*</text>单位</view>
				<view class="input-icon">
					<input class="input" v-model="form.danwei" :disabled="disabled" placeholder="请输入内容" />
					<view class="icon hide iconfont icon-youjiantou"></view>
				</view>
			</view>
			
			<view class="input-item">
				<view class="label">合同编号</view>
				<view class="input-icon">
					<input class="input" v-model="form.hetong_sn" :disabled="disabled" placeholder="请输入内容" />
					<view class="icon hide iconfont icon-youjiantou"></view>
				</view>
			</view>
		
			<view class="input-item">
				<view class="label">备注</view>
				<view class="input-icon">
					<input class="input" v-model="form.beizhu" :disabled="disabled" placeholder="请输入内容" />
					<view class="icon hide iconfont icon-youjiantou"></view>
				</view>
			</view>
		</view>
		
		<view class="input-box img-box">
			<view class="input-box-title">图片</view>
			<!-- 上传图片 -->
			<view class="upload-com">
				  <view class="img" 
					v-for="(item,index) in form.images"
					:key="index"
				  >
						  <image mode="scaleToFill" :src="item" @click="previewImage(index)"></image>
						  <view 
							class="del" 
							@click.stop="deleteImg(item)"
							v-if="!disabled"
						  ><view class="icon iconfont icon-guanbi1"></view></view>
				  </view>
				  <view class="upload-com-btn" @click="uploadImgs" v-if="!disabled">
						<view class="icon iconfont icon-jiahao1"></view>
				  </view>
			</view>
		</view>
				
		<view class="bottom-btn" v-if="!disabled">
				<button type="primary" class="btn-confirm" size="mini" @click="confirmFun">保存</button>
		</view>
		
	</view>
</template>

<script setup>
	import {
	    onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom
	} from "@dcloudio/uni-app";
	import { ref } from "vue"
	import configure from '@/configure/server/index.js'
	import { GetCangkuList, AddCangkuItem, EditCangku } from "@/configure/api/cangku.js"
	import { showErrMsg, showSuccessMsg } from "@/utils/msg";
	import { getUserInfo } from "@/utils/getUserInfo.js"
	import { validatePlusFloatWithTwo } from "@/utils/validate.js";
	import qiniuUploader from "@/utils/qiniuUploader";
	
	const cangkus = ref([])
	const types = ref([
		{
			label: '入库',
			value: 0
		},
		{
			label: '出库',
			value: 1
		}
	])
	const statusArr = ref([
		{
			label: '入库',
			value: 0
		}
	])
	const form = ref({
		id: 0,
		type: 0,
		name: '',
		count: '',
		beizhu: '',
		images: [],
		danwei: '',
		hetong_sn: '',
		status: 0
	})
	
	const confirmFun = async() => {

		let { 
			id,
			type,
			name,
			count,
			beizhu,
			images,
			danwei,
			hetong_sn,
			status
		} = form.value;

		let opt = {
			type,
			name,
			count,
			beizhu,
			images: images.join(","),
			danwei,
			hetong_sn,
			status: statusArr.value[status].value
		}
		
		if(stateData.value == 'add' || stateData.value == 'addMore'){
			opt.userid = userInfo.value.id
			opt.id = cangkus.value[id].value // 销售员id
		}else if(stateData.value == 'edit'){
			opt.id = id
		}
		
		
		if(!name){
			showErrMsg(`请输入名称!`)
			return
		}
		
		if(!count){
			showErrMsg(`请输入数量!`)
			return
		}else if(!validatePlusFloatWithTwo(count)){
			showErrMsg(`数量必须为正数字!`)
			return
		}
		
		if(!danwei){
			showErrMsg(`请输入单位!`)
			return
		}
		
		if(stateData.value == 'add' || stateData.value == 'addMore'){
			let res = await AddCangkuItem(opt);
			if(res.code == 200){
				showSuccessMsg("创建成功!");
				uni.navigateBack({
					delta: -1
				});
			}
		} else if(stateData.value == 'edit'){
			let res = await EditCangku(opt);
			if(res.code == 200){
				showSuccessMsg("编辑成功!");
				uni.navigateBack({
					delta: -1
				});
			}
		}
		
	}
	
	const cangkuChange = (e) => {
		form.value.id = e.detail.value
	}
	
	const typeChange = (e) => {
		let { value } = e.detail
		form.value.type = value
		form.value.status = 0

		if(value == "0"){
			statusArr.value = [
				{
					label: '入库',
					value: 0
				}
			]
		}else if(value == "1"){
			statusArr.value = [
				{
					label: '销售',
					value: 1
				},
				{
					label: '损耗',
					value: 2
				}
			]
		}
	}
	
	const statusChange = (e) => {
		form.value.status = e.detail.value
	}
	
	const GetCangkuListFun = async (cangkuid) => {
		let res = await GetCangkuList();
			res = res.data;
		// debugger
		if(res.length){
			cangkus.value = res.map(v=>{
				return{
					label: v.name,
					value: v.id
				}
			})
			
			if(cangkuid){
				cangkus.value.forEach((v,i)=>{
					if(v.value == cangkuid){
						form.value.id = i
					}
				})
				
			}
		}
	}
	
	//上传图片
	const uploadImgs = (e) => {   
		if( form.value.images.length > 5 ){
			uni.showToast({
			  title: '只能上传5张图片!',
			  icon: "none"
			});
			return false;
		}
		
		uni.chooseImage({
		  count: 6,
		  sizeType: ['original', 'compressed'],
		  sourceType: ['album', 'camera'],
		  success(resFile) {
	
			const filePath = resFile.tempFiles[0];
			
			qiniuUploader.upload(filePath.path, (res) => {
			
			  form.value.images.push(res.imageURL);
	
			}, (error) => {
			  console.error('error: ' + JSON.stringify(error));
			});
		  }
		});
		
	}
	
	//预览图片
	const previewImage = (index) => {
		let images = form.value.images;
		uni.previewImage({
			  current:images[index],    //  传 Number H5端出现不兼容 
			  urls: images
		});
	}
	
	//删除图片
	const deleteImg = (item) => {
	    form.value.images.forEach((v, i, arr) => {
	      if (v == item) {
	        form.value.images.splice(i, 1);
	      }
	    });
	}
	
	const initQiniu = () => {
		uni.request({
			url: `${configure.server.host}/qiniu/getToken`,
			success: function (res) {
			  let token = res.data.token;
			  var options = {
				region: 'ECN', // 华东
				uptoken: token, //七牛token
				fileHead: "manage", //上传前缀
				domain: 'https://cdn.yunnanyunyin.com/' //下载前缀
			  };
			  qiniuUploader.init(options);
			}
		})
	}
	
	const stateData = ref('add')
	const disabled = ref(false)
	const userInfo = ref()
	onLoad((detail)=>{
		
		let { state, name, cangkuid, pingming, number, hetong_sn } = detail
		
		stateData.value = state
				
		disabled.value = ( state == 'read' )
		
		if(state == 'addMore'){
			form.value.name = name
		}
		
		if(pingming){
			form.value.name = pingming
		}
		
		if(number){
			form.value.count = number
		}
		
		if(hetong_sn){
			form.value.hetong_sn = hetong_sn
		}
		
		GetCangkuListFun(cangkuid)
		initQiniu()
		
		getUserInfo().then((res)=>{
			userInfo.value = res;
		})
	})
	
	onShow(()=>{
		
	})
	
</script>

<style lang="scss">
	.page-box{
		padding-bottom: 50rpx;
		
		.img-box{
			margin-top: 30rpx;
		}
		
		.upload-com{
		  display: flex;
		  flex-direction: row;
		  justify-content: flex-start;
		  flex-wrap: wrap;
		  box-sizing: border-box;
		  margin-top: 30rpx;
		  margin-bottom: 0;
		}
		
		.upload-com .img,.upload-com .upload-com-btn{
		  width:120rpx;
		  height:120rpx;
		  border-radius: 8rpx;
		}
		
		.upload-com .img{
		  position: relative;
		  margin-right: 35rpx;
		  margin-bottom: 35rpx;
		}
		
		.upload-com .img image{
		  width:120rpx;
		  height:120rpx;
		}
		
		.upload-com .upload-com-btn{
		  background: #f0f2f7;
		  display: flex;
		  flex-direction: row;
		  justify-content: center;
		  align-items: center;
		}
		
		.upload-com .upload-com-btn .icon{
		  color: #d2dae6;
		  font-size: 30rpx;
		}
		
		.upload-com .del{
		  width: 37rpx;
		  height: 37rpx;
		  font-size: 45rpx;
		  background: var(--mainColor);
		  color:#fff;
		  position: absolute;
		  right:0;
		  top:0;
		  border-radius: 100rpx;
		  transform: translateX(50%) translateY(-50%);
		  @include flex-center();
		  
		  .icon{
			  font-size: 22rpx;
			 color:#fff;
		  }
		}
	}	
</style>

